// pages/square/my.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "TA的帖子", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    listType: 0,
    classArr: [{
      id: 0,
      name: '最新'
    }, {
      id: 1,
      name: '最多赞'
    }],
    classId: 0,
    forumList: [],
    forumListGl: [], //攻略列表
    isHeightMode: false,

    authData: {
      authType: '0', //0表示使用登录弹窗  1表示使用完善昵称头像弹窗 2表示直接弹出头像昵称选择框
      authUsername: "false", //是否已经授权头像昵称
    },
    showLogin: false, //是否显示授权弹窗
    showWsInfoDom: false, //直接显示头像昵称弹窗
    showPrivacyFlag: app.globalData.showPrivacyFlag,

    openid: '',
    taOpenid: '',
    taUserId: '',
    is_nickAndHead: 0,
    shareTitle: '',
    shareImg: '',

    sort: 1, //1:最新 2：最热
    page: 1, //当前页数
    pageGl: 1,
    isLoadingEnd: 0, //0:数据未加载完 1:数据已加载完
    isLoadingEndGl: 0, //0:数据未加载完 1:数据已加载完
    isloading: false,

    userInfo: [],
    bgzTotal: 0,
    gzTotal: 0,
    likeTotal: 0,
    scTotal: 0,
    zanTotal: 0,
    isGz: 0,
    is_one_gl: 1, //是否是第一次加载攻略 1：是 2：不是
    headerUrl: '',
    gameList: [],
    isHaveMore: true,
    userId: ''
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },

  //method
  hotCircleCilck: function (event) {
    var tapId = event.currentTarget.id;
    this.addHeaderUrl();
    wx.navigateTo({
      url: '/pages/marketing/yglDetail?id=' + tapId
    })
  },

  chooseClass(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    this.setData({
      classId: id
    });

    //判断是切换的圈子还是攻略
    if (that.data.listType == 0) {
      //圈子
      if (id == 0) {
        //最新
        that.setData({
          sort: 0,
          page: 1,
          forumList: []
        });

        //缓存圈子是最新还是最多赞
        wx.setStorageSync('taQzSort', 0);
        //调用加载
        that.getList(1, 0, 0);
      } else {
        //推荐
        that.setData({
          sort: 1,
          page: 1,
          forumList: []
        });
        //缓存圈子是最新还是最多赞
        wx.setStorageSync('taQzSort', 1);
        //调用加载
        that.getList(1, 1, 0);
      }
    } else if (that.data.listType == 2) {
      //攻略
      if (id == 0) {
        //最新
        that.setData({
          sort: 0,
          pageGl: 1,
          forumListGl: []
        });

        //缓存攻略是最新还是最多赞
        wx.setStorageSync('taGlSort', 0);
        //调用加载
        that.getListGl(1, 0, 0);
      } else {
        //推荐
        that.setData({
          sort: 1,
          pageGl: 1,
          forumListGl: []
        });
        //缓存攻略是最新还是最多赞
        wx.setStorageSync('taGlSort', 1);
        //调用加载
        that.getListGl(1, 1, 0);
      }
    }

    /*if (id == 0) {
      //最新
      that.setData({
        sort: 1,
        page: 1,
        forumList: []
      });

      //调用加载
      that.getList(1, 1, 0);
    } else {
      //推荐
      that.setData({
        sort: 2,
        page: 1,
        forumList: []
      });
      //调用加载
      that.getList(1, 2, 0);
    }*/
  },

  //跳转至麓客局详情页
  goGameDetail(e) {
    var that = this;
    var row = e.currentTarget.dataset.index;
    var id = that.data.gameList[row].id;
    var gameOpenid = that.data.gameList[row].openid;
    that.addHeaderUrl();
    //跳转Ta的组局详情
    wx.redirectTo({
      url: '/pages/square/partDetail?id=' + id
    });
  },


  //热门话题跳转至话题详情
  goDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    if (id == that.data.tid) {
      return;
    }
    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/talk?tid=' + id
    });
  },

  //跳转至帖子详情
  goPostDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;

    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/commentDetail?id=' + id
    });
  },

  //将回跳url写入缓存
  addHeaderUrl() {
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array) {
      if (this.data.headerUrl == headerUrlList[headerUrlList.length - 1]) {
        //与上一个回跳链接相同则不添加
        return;
      }
      headerUrlList.push(this.data.headerUrl);
      wx.setStorageSync('headerUrlList', headerUrlList);
    } else {
      headerUrlList = [];
      headerUrlList.push(this.data.headerUrl)
      wx.setStorageSync('headerUrlList', headerUrlList);
    }
  },


  //点击圈子
  qz() {
    let that = this;
    that.setData({
      listType: 0,
      classId: wx.getStorageSync('taQzSort')
    })
  },
  ygl() {
    let that = this;
    that.setData({
      listType: 2,
      classId: wx.getStorageSync('taGlSort')
    });

    //判断是否是第一次调用
    if (that.data.is_one_gl == 1) {
      that.setData({
        is_one_gl: 0,
      });
      that.getListGl(1, 0, 0);
    }
  },
  //点击麓客局
  lkj() {
    let that = this;
    that.setData({
      listType: 1
    })
  },
  //删除某个帖子
  delPost(e) {
    let that = this;
    that.setData({
      showDelDom: true
    })
  },
  //确认删除
  sureDel() {
    let that = this;
    that.setData({
      showDelDom: false
    });
  },
  //取消
  cancel() {
    let that = this;
    that.setData({
      showDelDom: false
    })
  },
  // 预览图片
  previewImage(e) {
    let {
      sources,
      index
    } = e.currentTarget.dataset
    sources.filter(i => {
      i.type = i.type == 2 ? 'video' : 'image'
      i.poster = i.imgUrl
    })
    console.log("sources:", sources)
    wx.previewMedia({
      sources,
      current: index
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = res.windowWidth;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },
  // 视频加载完成，改变视频的宽高
  videometa2(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = 331;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },
  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    wx.getImageInfo({
      src: e.currentTarget.dataset.sources[0],
      success: function (res) {
        console.log(res.width, res.height); // 这里获取的宽高是正确的
        res.height >= res.width && this.setData({
          isHeightMode: true
        })
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },

  //收藏
  collect(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addSc.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].collect.status']: "1",
              ['forumList[' + index + '].collect.num']: parseInt(that.data.forumList[index].collect.num) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].collect.status']: "0",
              ['forumList[' + index + '].collect.num']: parseInt(that.data.forumList[index].collect.num) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //处理完善信息
  addWxInfo() {
    this.setData({
      ['authData.authType']: 1,
      showLogin: true
    });
  },

  //点赞
  help(e) {
    var that = this;
    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZan.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].help.status']: "1",
              ['forumList[' + index + '].help.num']: parseInt(that.data.forumList[index].help.num) + 1,
              zanTotal: parseInt(that.data.zanTotal) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].help.status']: "0",
              ['forumList[' + index + '].help.num']: parseInt(that.data.forumList[index].help.num) - 1,
              zanTotal: parseInt(that.data.zanTotal) + 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //攻略点赞
  helpGl(e) {
    var that = this;
    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZanGl.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumListGl[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumListGl[' + index + '].is_zan']: "1",
              ['forumListGl[' + index + '].zan_number']: parseInt(that.data.forumListGl[index].zan_number) + 1
            })

          } else {
            that.setData({
              ['forumListGl[' + index + '].is_zan']: "0",
              ['forumListGl[' + index + '].zan_number']: parseInt(that.data.forumListGl[index].zan_number) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //点击关注
  addGz(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var flag = e.currentTarget.dataset.flag;
    var isGz = flag == 'add' ? 1 : 0;
    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addGz.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'taOpenid': that.data.taOpenid,
        'taUserId':that.data.taUserId,
        'flag': flag
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          that.setData({
            isGz: isGz
          });

          //处理成员数
          if (flag == 'add') {
            that.setData({
              bgzTotal: parseInt(that.data.bgzTotal) + 1
            });
          } else {
            that.setData({
              bgzTotal: parseInt(that.data.bgzTotal) - 1
            });
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    var taOpenid = options.openid;
    var taUserId = options.userId;
    //taOpenid = 'o3p135J-M7bQ3-_vpVvxIG-jU3PE';
    if (taOpenid == null || taOpenid == '' || taUserId == '' || taUserId == undefined || taOpenid == undefined) {
      app.showTip('抱歉,未获取到用户信息哦');
      setTimeout(function () {
        wx.switchTab({
          url: '/pages/square/index'
        })
      }, 2000);
      return;
    } else {
      that.setData({
        taOpenid: taOpenid,
        taUserId: taUserId
      });
    }

    //赋值回跳本页的url
    that.setData({
      headerUrl: '/pages/square/ta?openid=' + taOpenid + "&userId=" + taUserId
    });
    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    }

    //获取发布麓客局标识
    var listType = wx.getStorageSync('listType');
    if (listType == 1 || listType == '1') {
      that.setData({
        listType: 1
      });
      //清空缓存
      wx.setStorageSync('listType', 0);
    }

    //初始化圈子和攻略最新或推荐排序的缓存
    wx.setStorageSync('taQzSort', 0);
    wx.setStorageSync('taGlSort', 0);

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getTaPageInfo(res.data.openid, taOpenid, taUserId);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getTaPageInfo(openid, taOpenid, taUserId);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本业数据
  getTaPageInfo(openid, taOpenid, taUserId) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getTaPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        taOpenid: taOpenid,
        taUserId: taUserId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            forumList: res.data.forumList,
            isGz: res.data.isGz,
            is_nickAndHead: res.data.is_nickAndHead,
            isLoadingEnd: res.data.isLoadingEnd,
            userInfo: res.data.userInfo,
            bgzTotal: res.data.bgzTotal,
            gzTotal: res.data.gzTotal,
            likeTotal: res.data.likeTotal,
            scTotal: res.data.scTotal,
            zanTotal: res.data.zanTotal,
            gameList: res.data.gameList
          });
        } else if (res.data.status == 100) {
          //跳转至个人主页
          wx.redirectTo({
            url: '/pages/square/my'
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //接收子组件电话授权及头像昵称授权后后返回的值
  returnVal(e) {

    //授权完头像昵称
    this.setData({
      is_nickAndHead: e.detail.is_nickAndHead
      //['userInfo.head']: e.detail.head,
      //['userInfo.nickname']: e.detail.nickname
    });

    app.showTip('个人信息已完善');
  },

  //上拉获取数据
  getList(page, sort, pageAdd) {
    var that = this;
    this.setData({
      isloading: true
    });
    console.log('加载更多');
    wx.showLoading({
      title: '加载中'
    });

    wx.request({
      url: that.data.baseUrl + 'getForumListForWhere.php',
      method: 'POST',
      data: {
        'tid': 0,
        'taOpenid': that.data.taOpenid,
        'tableRow': 'openid',
        'openid': that.data.openid,
        'page': page,
        'sort': wx.getStorageSync('taQzSort') + 1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (pageAdd == 1) {
            that.setData({
              page: parseInt(that.data.page) + 1
            });
          }
          that.setData({
            isLoadingEnd: res.data.isLoadingEnd,
            forumList: that.data.forumList.concat(res.data.forumList),
            isloading: false
          });
        } else {
          app.showTip(res.data.msg);
          that.setData({
            isloading: false,
            isLoadingEnd: 1
          });
        }
      },
      fail: function (res) {
        wx.hideLoading();
        that.setData({
          isloading: false,
          isLoadingEnd: 1
        })
      }
    });
  },

  //上拉获取数据-攻略
  getListGl(page, sort, pageAdd) {
    var that = this;
    this.setData({
      isloading: true
    });
    console.log('加载更多');
    wx.showLoading({
      title: '加载中'
    });

    wx.request({
      url: that.data.baseUrl + 'getForumListGlForWhere.php',
      method: 'POST',
      data: {

        'openid': that.data.taOpenid,
        'page': page,
        'sort': wx.getStorageSync('taGlSort') + 1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (pageAdd == 1) {
            that.setData({
              pageGl: parseInt(that.data.pageGl) + 1
            });
          }
          that.setData({
            isLoadingEndGl: res.data.isLoadingEnd,
            forumListGl: that.data.forumListGl.concat(res.data.forumList),
            isloading: false
          });
        } else {
          app.showTip(res.data.msg);
          that.setData({
            isloading: false,
            isLoadingEndGl: 1
          });
        }
      },
      fail: function (res) {
        wx.hideLoading();
        that.setData({
          isloading: false,
          isLoadingEndGl: 1
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    //暂停加载或数据已加载完了直接返回空
    if (this.data.listType == 0) {
      if (this.data.isloading || this.data.isLoadingEnd == 1) {
        console.log('end');
        return;
      }
      this.getList(parseInt(this.data.page) + 1, this.data.sort, 1);
    } else if (this.data.listType == 2) {
      if (this.data.isloading || this.data.isLoadingEndGl == 1) {
        console.log('end');
        return;
      }
      this.getListGl(parseInt(this.data.pageGl) + 1, this.data.sort, 1);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})